<template>
    <div class="user-container">
        <el-card class="box-card">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item to="home"><span @click="clearPath">首页</span></el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户列表</el-breadcrumb-item>
            </el-breadcrumb>
            <el-row :gutter="20" class="user-search">
                <el-col :span="8">
                    <el-input @clear="getUsersList" v-model="queryInfo.query" placeholder="请输入要查找的用户的用户名" round
                              clearable>
                        <el-button @click="getUsersList" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" round @click="dialogVisible = true">添加用户</el-button>
                    <el-dialog
                        title="添加用户"
                        :visible.sync="dialogVisible"
                        width="50%"
                        @close="addDialogClosed">
                        <el-form :status-icon="true"
                                 :model="addForm"
                                 :rules="addFormRules"
                                 ref="addFormRef"
                                 label-width="100px"
                                 class="demo-ruleForm">
                            <el-form-item label="用户名" prop="username">
                                <el-input v-model="addForm.username"></el-input>
                            </el-form-item>

                            <el-form-item label="邮箱" prop="email">
                                <el-input v-model="addForm.email"></el-input>
                            </el-form-item>

                            <el-form-item label="密码" prop="password">
                                <el-input v-model="addForm.password"></el-input>
                            </el-form-item>

                            <el-form-item label="电话号码" prop="mobile">
                                <el-input v-model="addForm.mobile"></el-input>
                            </el-form-item>
                        </el-form>
                        <span slot="footer" class="dialog-footer">
                            <el-button @click="dialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="addUser">确 定</el-button>
                        </span>
                    </el-dialog>
                </el-col>
            </el-row>
            <el-table
                border
                stripe
                :data="userList"
            v-loading="loading">
                <el-table-column
                    label="#"
                    type="index">
                </el-table-column>
                <el-table-column
                    prop="username"
                    label="用户名">
                </el-table-column>
                <el-table-column
                    prop="email"
                    label="邮箱">
                </el-table-column>
                <el-table-column
                    prop="mobile"
                    label="电话">
                </el-table-column>
                <el-table-column
                    prop="role_name"
                    label="权限">
                </el-table-column>
                <el-table-column
                    prop="mg_state"
                    label="用户状态">
                    <template slot-scope="scope">
                        <!--                        {{scope.row}}-->
                        <el-switch
                            @change="userStatusChange(scope.row)"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            v-model="scope.row.mg_state"
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-dialog
                            title="修改用户信息"
                            :visible.sync="editDialogVisible"
                            width="50%"
                            @close="editUserDialogClose">
                            <el-form :status-icon="true"
                                     :model="editUser"
                                     :rules="addFormRules"
                                     ref="editUserRef"
                                     label-width="100px">
                                <el-form-item label="用户名">
                                    <el-input disabled v-model="editUser.username"></el-input>
                                </el-form-item>

                                <el-form-item label="邮箱" prop="email">
                                    <el-input v-model="editUser.email"></el-input>
                                </el-form-item>

                                <el-form-item label="电话号码" prop="mobile">
                                    <el-input v-model="editUser.mobile"></el-input>
                                </el-form-item>
                            </el-form>
                            <span slot="footer" class="dialog-footer">
                                        <el-button @click="editDialogVisible = false">取 消</el-button><el-button
                                type="primary"
                                @click="submitChange">确 定</el-button>
                                    </span>
                        </el-dialog>

                        <!--修改-->
                        <el-tooltip :enterable="false" class="item" effect="dark" content="编辑"
                                    placement="top-start">

                            <el-button @click="showEditDialog(scope.row)" size="mini" type="primary"
                                       icon="el-icon-edit"
                                       circle>
                            </el-button>
                        </el-tooltip>
                        <!--分配用户-->
                        <el-tooltip :enterable="false" class="item" effect="dark" content="分配用户"
                                    placement="top-start">
                            <el-button @click="editUserRight(scope.row)" size="mini" type="success"
                                       icon="el-icon-setting" circle></el-button>
                        </el-tooltip>

                        <!--删除-->
                        <el-tooltip :enterable="false" class="item" effect="dark" content="删除"
                                    placement="top-start">
                            <el-button @click="removeUserById(scope.row.id)" size="mini" type="danger"
                                       icon="el-icon-delete" circle></el-button>
                        </el-tooltip>
                        <el-dialog
                            title="分配权限"
                            :visible.sync="editRoleRightsDialog"
                            width="50%"
                            @close="userEditRightDialog">
                            <div>当前用户名: {{editUserRole.username}}</div>
                            <div>当前权限: {{editUserRole.role_name}}</div>
                            <div>
                                <el-select v-model="postUserRoleForRight.modifyRightId" placeholder="请选择">
                                    <el-option
                                        v-for="item in editUserRole.allRoles"
                                        :key="item.id"
                                        :label="item.roleName"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                            <span slot="footer" class="dialog-footer">
                            <el-button @click="editRoleRightsDialog = false">取 消</el-button>
                            <el-button type="primary" @click="postEditUserRight">确 定</el-button>
                            </span>
                        </el-dialog>
                    </template>
                </el-table-column>
            </el-table>
            <div>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1, 2, 3, 5]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </el-card>
    </div>
</template>

<script>
    export default {
        name: "User",
        data() {
            return {
                userList: [],
                total: 0,
                queryInfo: {
                    query: '',
                    pagenum: 1,
                    pagesize: 2,
                },
                dialogVisible: false,
                //添加表单数据
                addForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                editUser: {},
                editDialogVisible: false,
                editRoleRightsDialog: false,
                editUserRole: {},
                postUserRoleForRight: {},
                loading:true,
                //表单验证规则对象
                addFormRules: {
                    // username: [
                    //     {required: true, message: '请输入用户名', trigger: 'blur'},
                    //     {min: 3, max: 10, message: '长度最少3~10个字符', trigger: 'blur'}
                    // ],
                    // email: [
                    //     {required: true, message: '请输入邮箱', trigger: 'blur'},
                    //     {min: 3, max: 10, message: '长度最少3~10个字符', trigger: 'blur'}
                    // ],
                    // password: [
                    //     {required: true, message: '请输入密码', trigger: 'blur'},
                    //     {min: 6, max: 15, message: '长度最少6~15个字符', trigger: 'blur'}
                    // ],
                    // mobile: [
                    //     {required: true, message: '请输入手机号码', trigger: 'blur', type: ''},
                    //     {min: 11, max: 11, message: '长度11个字符', trigger: 'blur'}
                    // ]
                },
            }
        },
        created() {
            this.getUsersList();
        },
        methods: {
            async getUsersList() {
                let res = await this.$http.get('users', {params: this.queryInfo})
                if (res.data.meta.status !== 200) {
                    return this.$notify.error('获取用户列表失败');
                } else {
                    // console.log(res.data.data.users)
                    // console.log(this.queryInfo.pagenum)
                    if (res.data.data.users.length === 0) {
                        this.queryInfo.pagenum--
                        await this.getUsersList()
                        return false;
                    }
                    this.userList = res.data.data.users;
                    this.total = res.data.data.total;
                    this.$notify.success('成功获取用户列表');
                }
            },
            handleSizeChange(newSize) {
                console.log(newSize)
                this.queryInfo.pagesize = newSize
                this.getUsersList()
            },
            handleCurrentChange(newPage) {
                console.log(newPage)
                this.queryInfo.pagenum = newPage
                this.getUsersList()
            },
            async userStatusChange(data) {
                console.log(data)
                let res = await this.$http.put(`users/` + data.id + `/state/` + data.mg_state);
                if (res.data.meta.status !== 200) {
                    return this.$notify.error('修改用户状态失败,请刷新重试')
                } else {
                    this.$notify.success('修改用户状态成功')
                }
            },
            addDialogClosed() {
                this.$refs.addFormRef.resetFields();
            },
            addUser() {
                this.$refs.addFormRef.validate(async valid => {
                    if (valid) {
                        let res = await this.$http.post('users', this.addForm)
                        console.log(res)
                        if (res.data.meta.status === 201) {
                            this.$notify.success('用户添加成功')
                            await this.getUsersList()
                            this.dialogVisible = false
                        } else {
                            this.$notify.error('用户添加失败，请查看输入的是否符合规则')
                        }
                    }
                })

            },
            showEditDialog(data) {
                this.editDialogVisible = true
                this.editUser = data;
                console.log(data)
            },
            async submitChange() {
                let res = await this.$http.put('users/' + this.editUser.id, {
                    email: this.editUser.email,
                    mobile: this.editUser.mobile
                })
                console.log(res)
                if (res.data.meta.status === 200) {
                    this.$notify.success('修改成功')
                    await this.getUsersList()
                    this.editDialogVisible = false
                } else {
                    this.$notify.error('修改失败')
                }
            },
            editUserDialogClose() {
                this.$refs.editUserRef.resetFields()
                console.log(this.userList)
            },
            removeUserById(id) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let res = await this.$http.delete('users/' + id)
                    if (res.data.meta.status === 200) {
                        this.$notify.success('删除成功')
                        // this.queryInfo.pagenum--
                        this.getUsersList()
                    } else {
                        this.$notify.error('删除失败')
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            clearPath() {
                window.sessionStorage.removeItem('path');
            },
            //分配权限
            async editUserRight(userInfo) {
                this.editUserRole = userInfo
                let res = await this.$http.get('roles')
                console.log(res.data.data)
                this.editUserRole.allRoles = res.data.data
                this.postUserRoleForRight.roleId = userInfo.id
                this.editRoleRightsDialog = true
                console.log(this.editUserRole)
                console.log(this.postUserRoleForRight)
            },
            async postEditUserRight() {
                console.log(this.postUserRoleForRight)
                let res = await this.$http.put('users/' + this.postUserRoleForRight.roleId + '/role', {rid: this.postUserRoleForRight.modifyRightId})
                if (res.data.meta.status === 200) {
                    this.$notify.success('修改成功')
                    await this.getUsersList()
                }
                this.editRoleRightsDialog = false
            },
            userEditRightDialog(){
                this.postUserRoleForRight={}
            },
        }
    }
</script>

<style scoped lang="less">
    .box-card {
        border-radius: 15px;

        .user-search {
            margin-bottom: 15px;

        }

        .el-dialog {
            box-sizing: border-box;
            padding-right: 80px !important;
        }
    }

</style>
